package com.xxhui.scrolldemo.View;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by hui on 2016/7/23.
 */
public class DrawViewByLayout extends View {

    private static final String TAG = "DrawViewByLayout" ;
    private int lastX;
    private int lastY;
    private int viewWidth;
    private int viewHeight;
    private Paint paint;

    public DrawViewByLayout(Context context) {
        super(context);
        initRes();
    }

    public DrawViewByLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initRes();
    }

    public void initRes(){
        // 给View设置背景颜色，便于观察
        setBackgroundColor(Color.RED);
        paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLACK);
        paint.setTextSize(20);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x = (int) event.getX();//获取以当前View为参考系的x坐标
        int y = (int) event.getY();//获取以当前View为参考系的y坐标
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                // 记录触摸点坐标
                lastX = x;
                lastY = y;
                Log.i(TAG, "onTouchEvent: down");
                break;
            case MotionEvent.ACTION_MOVE:
                int offsetX = x - lastX;
                int offsetY = y - lastY;
                //使用此差值的代表，每次Layout完毕后，相对着这个（lastX，lastY）坐标重绘
                layout(getLeft()+offsetX,//getLeft方法获取相对于父控件的位置
                        getTop()+offsetY,
                        getRight()+offsetX,
                        getBottom()+offsetY);
                Log.i(TAG, "onTouchEvent: x:"+x+" y:"+y+ " lastX:"+lastX+" lastY:"+lastY);
                break;
            case MotionEvent.ACTION_UP:
                layout(0,getTop(),getRight()-getLeft(),getBottom());
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //canvas.translate(viewWidth,viewHeight);
        canvas.drawText("Layout()",10,viewHeight/2,paint);
    }
}
